import axios from 'axios'
import { Toast } from 'vant';

//请求拦截
axios.interceptors.request.use(function (config) {
   Toast.loading({
      message: '加载中...',
      forbidClick: true
   });
   return config;
 }, function (error) {
   return Promise.reject(error);
 });

//响应拦截
axios.interceptors.response.use(function (response) {
   Toast.clear();
   return response;
 }, function (error) {
   return Promise.reject(error);
 });

 function ajax(url = '', params = {}, type = 'GET') {
   //定义promise对象
   let promise;
   return new Promise((resolve, reject)=>{
      //判断请求的方式
      if('GET' === type){
            //拼接请求字符串
            let paramsStr = '';
            Object.keys(params).forEach(key =>{
               paramsStr += key + '=' + params[key] + '&'
            });
            //过滤最后的&
            if(paramsStr !== ''){
               paramsStr = paramsStr.substr(0, paramsStr.lastIndexOf('&'))
            }
            // 完整路径
            url += '?' + paramsStr;
            //发送get请求
            promise = axios.get(url)
      }else if('POST' === type){
         promise = axios.post(url, params)
      }
      //返回请求的结果
      promise.then((response)=>{
         resolve(response.data)
      }).catch(error => {
         reject(error)
      })
   })
}

export default ajax
